//
//  HDUserManagerHeadCell.m
//  Dresshere
//
//  Created by ZhangPeng on 2017/12/29.
//  Copyright © 2017年 张朋. All rights reserved.
//

#import "HDUserManagerHeadCell.h"
#import "DHMemberExclusiveViewController.h"
#import "QBImagePickerController.h"
#import "UploadImageModel.h"
#import "DHYuYueController.h"
#import "DHChangeNicknameController.h"
#import <AVFoundation/AVCaptureDevice.h>
#import <AVFoundation/AVMediaFormat.h>

@interface HDUserManagerHeadCell()<QBImagePickerControllerDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (weak, nonatomic) IBOutlet UIImageView *headImgView;
@property (weak, nonatomic) IBOutlet UIButton *phoneLabel;
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
@property (weak, nonatomic) IBOutlet UIView *yuyueView;

@end

@implementation HDUserManagerHeadCell

- (void)awakeFromNib {
    [super awakeFromNib];
    self.headImgView.userInteractionEnabled = YES;
    [self.headImgView bk_whenTapped:^{
        UIActionSheet *actionsheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照", @"从相册中选择", nil];
        // 显示
        [actionsheet showInView:self.viewController.view];
    }];
}

- (IBAction)editAction:(id)sender {
    DHChangeNicknameController *vc = [[DHChangeNicknameController alloc] init];
    [self.viewController.navigationController pushViewController:vc animated:YES];
}

- (IBAction)yuyueAction:(id)sender {
    [[DHNetAPIClient shareDHNetAPIClient] request_user_consult_lastAndBlock:^(id data, NSError *error) {
        if (data) {
            NSInteger count = [[data objectForKey:@"count"] integerValue];
            if (count > 0) {
                DHYuYueController *vc = [[DHYuYueController alloc] init];
                [self.viewController.navigationController pushViewController:vc animated:YES];
            }else{
                [NSObject showHudTipStr:@"剩余预约穿搭顾问次数为0"];
            }
        }
    }];
    
}

- (IBAction)liangtiAction:(id)sender {
    [[DHNetAPIClient shareDHNetAPIClient] request_user_measure_lastAndBlock:^(id data, NSError *error) {
        if (data) {
            NSInteger count = [[data objectForKey:@"count"] integerValue];
            if (count > 0) {
                DHYuYueController *vc = [[DHYuYueController alloc] init];
                [self.viewController.navigationController pushViewController:vc animated:YES];
            }else{
                [NSObject showHudTipStr:@"剩余预约上门量体次数为0"];
            }
        }
    }];
}

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        if (authStatus ==AVAuthorizationStatusRestricted ||authStatus ==AVAuthorizationStatusDenied)  //用户已经明确否认了这一照片数据的应用程序访问
        {
            // 无权限 引导去开启
            //            NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            //            if ([[UIApplication sharedApplication]canOpenURL:url]) {
            //                [[UIApplication sharedApplication]openURL:url];
            //            }
            [NSObject showHudTipStr:@"请打开装衣汇的摄像头权限，打开后才能使用拍照功能"];
        }else{
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                UIImagePickerController *pickerCon = [[UIImagePickerController alloc]init];
                pickerCon.sourceType = UIImagePickerControllerSourceTypeCamera;
                pickerCon.allowsEditing = NO;//是否可编辑
                pickerCon.delegate = self;
                [self.viewController presentViewController:pickerCon animated:YES completion:nil];
            }else{
                NSLog(@"手机不支持相机");
            }
        }
    }else if (buttonIndex == 1){
        QBImagePickerController *imagePickerController = [[QBImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.allowsMultipleSelection = YES;
        imagePickerController.maximumNumberOfSelection = 1;
        imagePickerController.filterType = QBImagePickerControllerFilterTypePhotos;
        UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:imagePickerController];
        [self.viewController presentViewController:navigationController animated:YES completion:NULL];
    }
}

#pragma mark - QBImagePickerControllerDelegate
- (void)imagePickerController:(QBImagePickerController *)imagePickerController didSelectAsset:(ALAsset *)asset{
    [self dismissImagePickerController];
}

- (void)imagePickerControllerDidCancel:(QBImagePickerController *)imagePickerController{
    [self dismissImagePickerController];
}

- (void)imagePickerController:(QBImagePickerController *)imagePickerController didSelectAssets:(NSArray *)assets{
    NSMutableArray *imgs = [NSMutableArray array];
    [assets enumerateObjectsUsingBlock:^(ALAsset *asset, NSUInteger idx, BOOL * _Nonnull stop) {
        ALAssetRepresentation *rep = [asset defaultRepresentation];
        CGImageRef iref = [rep fullScreenImage];
        if (iref) {
            UIImage *img = [UIImage imageWithCGImage:iref];
            [imgs addObject:img];
        }
    }];
    if (imgs.count > 0) {
        [self uploadImage:[imgs objectAtIndex:0]];
    }
    [self dismissImagePickerController];
}

#pragma mark - UIImagePickerControllerDelegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    NSString *mediaType=[info objectForKey:UIImagePickerControllerMediaType];
    if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {//如果是拍照
        UIImage *image;
        //如果允许编辑则获得编辑后的照片，否则获取原始照片
        if (picker.allowsEditing) {
            image=[info objectForKey:UIImagePickerControllerEditedImage];//获取编辑后的照片
        }else{
            image=[info objectForKey:UIImagePickerControllerOriginalImage];//获取原始照片
        }
        [self uploadImage:image];
    }
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)uploadImage:(UIImage *)img{
    [[GlobalManager shareGlobalManager] upyunUploadImage:img andBlock:^(id data, NSError *error) {
        NSString *url = data;
        [[DHNetAPIClient shareDHNetAPIClient] request_user_photoWithParams:@{@"photo":url} andBlock:^(id data, NSError *error) {
            [[GlobalManager shareGlobalManager] refreshBasicInfoAndBlock:^(id data, NSError *error) {
                [self.headImgView dh_setImageURLString:url];
            }];
        }];
    }];
}

- (void)dismissImagePickerController{
    [self.viewController dismissViewControllerAnimated:YES completion:NULL];
}

// 会员独享事件
- (IBAction)memberExclusiveAction:(id)sender {
    DHMemberExclusiveViewController *meVC = [[DHMemberExclusiveViewController alloc] init];
    [self.viewController.navigationController pushViewController:meVC animated:YES];
}

- (void)updateCell{
    [self.headImgView dh_setImageURLString:[GlobalManager shareGlobalManager].user.photo];
    if ([GlobalManager shareGlobalManager].user.nickname.length > 0) {
        self.nameLabel.text = [GlobalManager shareGlobalManager].user.nickname;
    }else{
        self.nameLabel.text = @"未设置";
    }
    [self.phoneLabel setTitle:[NSString stringWithFormat:@"  %@",[Login curLoginUser].phone] forState:UIControlStateNormal];
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end
